#!/system/bin/sh

events=$1
# monitor_dir=$2
# monitor_file=$3

export PATH="/data/adb/magisk:/data/adb/ksu/bin:/data/adb/ap/bin:$PATH:/system/bin"

# ex: 7.1.1
buildVersion=$(getprop ro.build.version.release)
minBuildVersion="11"
IPV="iptables" # Default
IP6V="ip6tables" # Default
# ex: 7.1.1 -> 7
buildVersionMajor=${buildVersion%%.*}
if [ "$buildVersionMajor" -ge "$minBuildVersion" ]; then
  IPV="iptables -w 100"
  IP6V="ip6tables -w 100"
fi

iptables="${IPV}"
ip6tables="${IP6V}"
logs="/data/adb/box/run"

rules_add() {
  date > "${logs}/net.log"
  iptables -t mangle -F LOCAL_IP_V4
  ip -4 a | busybox awk '/inet/ {print $2}' | grep -vE "^127.0.0.1" | while read -r local_ipv4 ; do
    ${iptables} -t mangle -A LOCAL_IP_V4 -d $local_ipv4 -j ACCEPT
    rv1=$?
    ${iptables} -t nat -A LOCAL_IP_V4 -d $local_ipv4 -j ACCEPT
    rv2=$?
    ( [ $rv1 = "0" ] || [ $rv2 = "0" ] ) && echo "[Info]: local ip is $local_ipv4, anti-loopback rule has been inserted" >> ${logs}/net.log 2>&1
  done

  ip6tables -t mangle -F LOCAL_IP_V6
  ip -6 a | busybox awk '/inet6/ {print $2}' | grep -vE "^fe80|^::1|^fd00" | while read -r local_ipv6 ; do
    ${ip6tables} -t mangle -A LOCAL_IP_V6 -d $local_ipv6 -j ACCEPT
    [ $? = "0" ] && echo "[Info]: local ip is $local_ipv6, anti-loopback rule has been inserted" >> ${logs}/net.log 2>&1
  done
}

if [ "$events" = "w" ]; then
  if [ -f "/data/adb/box/run/box.pid" ]; then
    rules_add
  fi
fi